package com.hnyfkj.jyindustry.biz.admin.service.impl;

import com.hnyfkj.jyindustry.biz.admin.service.SysUserTokenService;
import com.hnyfkj.jyindustry.common.oauth2.TokenGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserTokenServiceImpl implements SysUserTokenService {

	private static Logger logger = LoggerFactory.getLogger(SysUserTokenServiceImpl.class);

	// token过期时间30分钟
	@Value("${tokenExpireTime}")
	public int EXPIRETIME;
	// 前缀
	private final String PREFIX = "authToken:";

	@Resource
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public String insert(final Long userId) {
		final String token = TokenGenerator.generateValue();
		stringRedisTemplate.opsForValue().set(PREFIX + token, userId + "", EXPIRETIME, TimeUnit.MINUTES);
		return token;
	}

	@Override
	public void update(final String token) {
		stringRedisTemplate.expire(PREFIX + token, EXPIRETIME, TimeUnit.MINUTES);
	}

	@Override
	public String getUserIdByToken(final String token) {
		final String userId = stringRedisTemplate.opsForValue().get(PREFIX + token);
		if (userId != null) {
			// 获取到用户id时，更新token时间
			update(token);
		}
		return userId;
	}

	@Override
	public void delete(final String token) {
		stringRedisTemplate.delete(PREFIX + token);
	}

}
